import sys, socket, time, threading, json

# Log lock makes log output thread safe
loglock = threading.Lock()

def log(msg, ip):
    loglock.acquire()
    try:
        print('[%s]: \n[IP:%s]\n%s\n' % (time.ctime(), ip, msg.strip()))
        sys.stdout.flush()
    finally:
        loglock.release()

# Transport class, with source as the source and target as the target
# Forwarding principle: the server establishes a connection with the client, and the server establishes a connection with the forwarding target
# The server gets two sock s and uses PipeThread to exchange messages
class PipeThread(threading.Thread):

    def __init__(self, source, target):
        threading.Thread.__init__(self)
        self.source = source
        self.target = target

    def run(self):
        while True:
            try:
                data = self.source.recv(1024)
                if "index.m3u8" in str(data):
                    print (data)
                if not data:
                    break
                self.target.send(data)
            except Exception as e:
                print("something wrong",e)
                break


class Forwarding(threading.Thread):
    def __init__(self, port, targethost, targetport):
        threading.Thread.__init__(self)
        self.targethost = targethost
        self.targetport = targetport
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind(('127.0.0.1', port))
        self.sock.listen(10)

    def run(self):
        while True:
            client_fd, client_addr = self.sock.accept()
            target_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            target_fd.connect((self.targethost, self.targetport))
            PipeThread(target_fd, client_fd).start()
            PipeThread(client_fd, target_fd).start()


# two direct pipe


if __name__ == '__main__':
    Forwarding(8888, '39.106.152.15', 8080).start()
    sys.exit(1)